package com.zbf.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/6/22  14:30
 * 描述:
 */
@Configuration
public class RequestRateLimiterConfig {


    @Bean("keyResolver")
    @Primary
    public KeyResolver urlKeyResolver(){//根据url
        return new KeyResolver() {
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }


    @Bean
    public KeyResolver apiKeyResolver(){//根据用户来限流
        return new KeyResolver() {
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getQueryParams().getFirst("userName"));
            }
        };

    }


    @Bean
    public KeyResolver ipKeyResolver(){//根据ID
        return new KeyResolver() {
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
            }
        };
    }

}
